package cn.wolfcode.luowowo.redis.service.impl;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.util.Consts;
import cn.wolfcode.luowowo.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //存储验证码到数据库
    @Override
    public void setVerifyCode(String phone, String code) {
        //使用枚举设置key值 ,设置失效值
        String key = RedisKeys.VERIFY_CODE.join(phone);
        redisTemplate.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    //获取验证码是否正确 再进行注册
    @Override
    public String getKey(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String value = redisTemplate.opsForValue().get(key);
        return value;
    }

    //将登入用户的信息存入redis中
    @Override
    public String setToken(UserInfo userInfo) {
        //获取随机的key
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisKeys.TOKEN_CODE.join(token);
        //将对象转换为json格式存入
        String json = JSON.toJSONString(userInfo);
        //设置失效
        redisTemplate.opsForValue().set(key, json, RedisKeys.TOKEN_CODE.getTime(), TimeUnit.SECONDS);
        return token;
    }


    //获取当前用户 (查看redis中单前用户的可以是否失效,判断要不要重新登入)
    @Override
    public UserInfo getToken(String token) {
        //判空
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.TOKEN_CODE.join(token);
        //判断redis数据库中又没这个key
        if (redisTemplate.hasKey(key)) {
            String value = redisTemplate.opsForValue().get(key);
            //将value转换成userinfo对象
            UserInfo userInfo = JSON.parseObject(value, UserInfo.class);
            //重置30分钟
            redisTemplate.expire(key, RedisKeys.TOKEN_CODE.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }

        return null;
    }
}
